package com.vcc.boss.core.resolver;

import com.vcc.core.annotations.CurrentRole;
import com.vcc.core.exception.PermissionException;
import com.vcc.core.exception.SignInException;
import com.vcc.data.entity.Role;
import com.vcc.service.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.util.Arrays;
import java.util.Optional;

public class CurrentRoleMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private RoleService roleService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(Role.class) && parameter.hasParameterAnnotation(
                CurrentRole.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        if (StringUtils.isEmpty(webRequest.getAttribute("userId", RequestAttributes.SCOPE_REQUEST))) {
            throw new SignInException("登陆失效");
        }
        CurrentRole currentRole = Optional
                .ofNullable(parameter.getParameterAnnotation(CurrentRole.class))
                .orElseThrow(() -> new SignInException("登陆失效"));
        Long userId = (Long) webRequest.getAttribute("userId", RequestAttributes.SCOPE_REQUEST);
        Role role = roleService.getRole(userId);
        if (currentRole.verifyRoleList().length > 0) {
            if (!Arrays.asList(currentRole.verifyRoleList()).contains(role.getCode())) {
                throw new PermissionException("权限不够");
            }
        }
        return role;
    }
}
